package com.example.shake;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.location.Address;
import android.location.Geocoder;
import android.util.Log;

import java.io.IOException;
import java.util.List;


import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import com.example.shake.util.DateUtil;

@RequiresApi(api = Build.VERSION_CODES.M)
@SuppressLint("MissingPermission")

public class MainActivity extends AppCompatActivity implements SensorEventListener {

    private TextView tv_shake;
    private SensorManager mSensorManager; // 声明一个传感管理器对象
    private Vibrator mVibrator; // 声明一个震动器对象
    private LocationManager mLocationManager;
    double latitude = 0;
    double longitude = 0;

    //    private ConstraintLayout main_xml;
    private ImageView up;
    private ImageView down;
    private ObjectAnimator upAnimation;
    private ObjectAnimator downAnimation;
    private TranslateAnimation trans_up;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_shake = findViewById(R.id.tv_shake);
        up = findViewById(R.id.My_up);
        down = findViewById(R.id.My_down);
//        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(AppCompatActivity.LAYOUT_INFLATER_SERVICE);
//        main_xml = (ConstraintLayout)layoutInflater.inflate(R.layout.activity_main, null);

        hideActionBar();

        // 获取传感管理器对象
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        //提供位置定位服务的位置管理器对象,中枢控制系统
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // 请求权限
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,
                    android.Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
            Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
        }
        // 获取震动器对象
        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        //初始化动画
        initAnimation();
    }

    //隐藏菜单栏
    protected void hideActionBar() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) { actionBar.hide(); }
    }

    private void initAnimation() {

        downAnimation = ObjectAnimator.ofFloat(down, "translationY", 0, 200, 0);
        downAnimation.setDuration(2000);
        trans_up = new TranslateAnimation(0, 0, 0, -200);
        trans_up.setDuration(1000);
        final TranslateAnimation up2 = new TranslateAnimation(0, 0, -200, 0);
        up2.setDuration(1000);


        AnimationSet setup = new AnimationSet(false);
        setup.addAnimation(trans_up);

        trans_up.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                up.clearAnimation();
                up.startAnimation(up2);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    class MyLocationListener implements LocationListener{
        @Override
        public void onLocationChanged(@NonNull Location location) {
            latitude = location.getLatitude(); // 纬度
            longitude = location.getLongitude(); // 经度
        }
    }

    public String getAddress(double lnt , double lat){

        try{
            Geocoder geocoder = new Geocoder(this);
            boolean flag = Geocoder.isPresent();
            Log.e("thistt", "the flag is " + flag);
            StringBuilder stringBuilder = new StringBuilder();
            try {
                //根据经纬度获取地理位置信息---这里会获取最近的几组地址信息，具体几组由最后一个参数决定
                System.out.println("lat:" + lat + "lnt:" + lnt);
                List<Address> addresses = geocoder.getFromLocation(lat , lnt, 1);
                System.out.println(addresses.size());

                if (addresses.size() > 0) {
                    Address address = addresses.get(0);
                    for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                        //每一组地址里面还会有许多地址。这里我取的前2个地址。xxx街道-xxx位置
                        if(i == 0) {
                            stringBuilder.append(address.getAddressLine(i)).append("-");
                        }

                        if(i == 1){
                            stringBuilder.append(address.getAddressLine(i));
                            break;
                        }
                    }
                    //                stringBuilder.append(address.getCountryName()).append("_");//国家
                    //                stringBuilder.append(address.getFeatureName()).append("_");//周边地址
                    //                stringBuilder.append(address.getLocality()).append("_");//市
                    //                stringBuilder.append(address.getPostalCode()).append("_");
                    //                stringBuilder.append(address.getCountryCode()).append("_");//国家编码
                    //                stringBuilder.append(address.getAdminArea()).append("_");//省份
                    //                stringBuilder.append(address.getSubAdminArea()).append("_");
                    //                stringBuilder.append(address.getThoroughfare()).append("_");//道路
                    //                stringBuilder.append(address.getSubLocality()).append("_");//香洲区
                    //                stringBuilder.append(address.getLatitude()).append("_");//经度
                    //                stringBuilder.append(address.getLongitude());//维度
                    Log.d("thistt", "地址信息--->" + stringBuilder);
                }
            } catch (IOException e) {
                Toast.makeText(this, "报错", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }

            return stringBuilder.toString();

        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }


    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销当前活动的传感监听器
        mSensorManager.unregisterListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 位置监听
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, new MyLocationListener());
        // 给加速度传感器注册传感监听器
        mSensorManager.registerListener(this,
                mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
                SensorManager.SENSOR_DELAY_NORMAL);
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    public void onSensorChanged(SensorEvent event) {
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
            // values[0]:X轴，values[1]：Y轴，values[2]：Z轴
            float[] values = event.values;
            String adr = "";
            if ((Math.abs(values[0]) > 12 || Math.abs(values[1]) > 12
                    || Math.abs(values[2]) > 12)) {
                if(longitude != 0 && latitude != 0){
                    adr = getAddress(longitude, latitude);
                }else{
                    adr = "室内";
                }
                up.startAnimation(trans_up);

//                main_xml.setBackground(getDrawable(R.drawable.bg_2));
//                imageView_1.setVisibility(View.INVISIBLE);
//                imageView_2.setVisibility(View.VISIBLE);

                tv_shake.setText(DateUtil.getNowTime() + "你在" + adr + "成功摇一摇");
                // 提示用户
                mVibrator.vibrate(500);
                downAnimation.start();
            }
        }
    }

    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
}